package com.visikard.ui.fragment;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;

import com.visikard.application.Constant;
import com.visikard.ui.R;
import com.visikard.ui.activity.CouponBuilderActivityV3;
import com.visikard.utility.Utils;

public class CreateCouponFragment extends BaseFragment {
	// setArguments-->onAttach-->onCreate-->onCreateView-->onActivityCreated
	// onDestroyView-->onDestroy-->onDetach

	private CouponBuilderActivityV3 me;
	private View mView;
	final int CAMERA_CAPTURE = 1;
	final int PICK_GALLERY = 2;

	private void initControls(View view) {

		((Button) view.findViewById(R.id.button_camera)).setOnClickListener(new MyOnClickListener());
		((Button) view.findViewById(R.id.button_gallery)).setOnClickListener(new MyOnClickListener());
		((Button) view.findViewById(R.id.button_back)).setOnClickListener(new MyOnClickListener());
	}

	@Override
	public void setArguments(Bundle args) {
		// TODO Auto-generated method stub
		super.setArguments(args);
	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		me = (CouponBuilderActivityV3) getActivity();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.coupon_builder_24v2, null);
		initControls(mView);
		return mView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

	}

	private class MyOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
				case R.id.button_back:
					getActivity().finish();
					break;
				case R.id.button_camera:
					try {
						ContentValues values = new ContentValues();
						values.put(MediaStore.Images.Media.TITLE, "Image File name");
						Uri mCapturedImageURI = me.getContentResolver().insert(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
						Intent intentPicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
						startActivityForResult(intentPicture, CAMERA_CAPTURE);
					}
					catch (ActivityNotFoundException anfe) {
						// display an error message
						String errorMessage = "Whoops - your device doesn't support capturing images!";
						Utils.showToast(me, errorMessage, 0);

					}
					break;
				case R.id.button_gallery:
					try {
						Intent i = new Intent(Intent.ACTION_PICK,
								android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
						startActivityForResult(i, PICK_GALLERY);
					}
					catch (ActivityNotFoundException anfe) {
						// display an error message
						String errorMessage = "Whoops - your device doesn't support capturing images!";
						Utils.showToast(me, errorMessage, 0);

					}
					break;
				default:
					break;
			}
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == me.RESULT_OK) {
			if (requestCode == CAMERA_CAPTURE) {

				Cursor cursor = me.getContentResolver().query(Media.EXTERNAL_CONTENT_URI,
						new String[] { Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION },
						Media.DATE_ADDED, null, "date_added DESC");
				if (cursor != null && cursor.moveToFirst()) {
					String picturePath = "";

					do {
						picturePath = cursor.getString(cursor.getColumnIndex(Media.DATA));
						break;
					}
					while (cursor.moveToNext());
					cursor.close();

					CouponCameraPreviewFragment couponCameraPreviewFragment = (CouponCameraPreviewFragment) getFragmentManager()
							.findFragmentByTag(Constant.COUPON_CAMERA_FRAGMENT_TAG);
					if (couponCameraPreviewFragment == null) {
						couponCameraPreviewFragment = new CouponCameraPreviewFragment();
					}
					Bundle bundle = new Bundle();
					bundle.putString("path", picturePath);

					couponCameraPreviewFragment.setArguments(bundle);
					Utils.toFragment(getFragmentManager(), couponCameraPreviewFragment,
							Constant.COUPON_CAMERA_FRAGMENT_TAG, R.id.framelayout_coupon_builder);

				}

			}
			else if (requestCode == PICK_GALLERY) {
				Uri selectedImage = data.getData();

				String[] filePathColumn = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION,
						MediaStore.Images.Media.PICASA_ID, MediaStore.Images.Media.PICASA_ID };
				Cursor cursor = me.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
				cursor.moveToFirst();
				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				String picturePath = cursor.getString(columnIndex);

				if (!picturePath.contains("http")) {
					cursor.close();
					CouponCameraPreviewFragment couponCameraPreviewFragment = (CouponCameraPreviewFragment) getFragmentManager()
							.findFragmentByTag(Constant.COUPON_CAMERA_FRAGMENT_TAG);
					if (couponCameraPreviewFragment == null) {
						couponCameraPreviewFragment = new CouponCameraPreviewFragment();
					}
					Bundle bundle = new Bundle();
					bundle.putString("path", picturePath);

					couponCameraPreviewFragment.setArguments(bundle);
					Utils.toFragment(getFragmentManager(), couponCameraPreviewFragment,
							Constant.COUPON_CAMERA_FRAGMENT_TAG, R.id.framelayout_coupon_builder);
				}
				else {
					cursor.close();
					Bitmap bm;
					File file = null;
					try {
						bm = BitmapFactory.decodeStream(me.getContentResolver().openInputStream(selectedImage));
						file = new File(me.getCacheDir(), "abc");
						try {
							file.createNewFile();
						}
						catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						// Convert bitmap to byte array

						ByteArrayOutputStream bos = new ByteArrayOutputStream();
						bm.compress(CompressFormat.PNG, 0 /* ignored for PNG */, bos);
						byte[] bitmapdata = bos.toByteArray();

						// write the bytes in file
						FileOutputStream fos = new FileOutputStream(file);
						try {
							fos.write(bitmapdata);
						}
						catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					catch (FileNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					CouponCameraPreviewFragment couponCameraPreviewFragment = (CouponCameraPreviewFragment) getFragmentManager()
							.findFragmentByTag(Constant.COUPON_CAMERA_FRAGMENT_TAG);
					if (couponCameraPreviewFragment == null) {
						couponCameraPreviewFragment = new CouponCameraPreviewFragment();
					}
					Bundle bundle = new Bundle();
					bundle.putString("path", file.getAbsolutePath());

					couponCameraPreviewFragment.setArguments(bundle);
					Utils.toFragment(getFragmentManager(), couponCameraPreviewFragment,
							Constant.COUPON_CAMERA_FRAGMENT_TAG, R.id.framelayout_coupon_builder);
				}

			}
		}
		else if (resultCode == me.RESULT_CANCELED) {

		}
	}

}
